// pages/join/join.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
const pay = require('../../services/pay.js');
var QQMapWX = require('../../map/qqmap-wx-jssdk.js');
var WxParse = require('../../lib/wxParse/wxParse.js');
var qqmapsdk;
var lati = null
var longi = null
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:true,
    question:[],
    imgUrls: [],
    goodsId:'',
    hotRecommend:[],
    goodsDetails:'',
    info:{},
    winHeight:'',
    openAttr:false,
    checkedSpecText: '请选择规格数量',
    number:1,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png",
    orderId:'',
    price:'',
    orderDetails:[],
    parent_id:'',
    businessAddress:{},
    amount:'',
    coupon_id:'',
    myInfo:'',
    type: '',//此为区别用户是参与别人分享的团还是自己自然下单。参与别人分享的为join,否则为self
    buyStatus: '',//非分享状态下，单独购买为0，参与团购为2
  },
  buyGoods(){
    this.setData({
      openAttr:true
    })
  },
// 下单购买(正常下单拼团)
  groupBuyGoods:function(e){
    this.setData({ buyStatus:1})
    let formId = e.detail.formId
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        // collectBackImage: "/static/images/detail_back.png",
        price: that.data.goodsDetails.info.retail_price
      });
    }else{//下单
        // 判断有无orderId,若有则请求参数中带上表示参加拼团，若无则不传表示发起拼团
        var data;
        if(that.data.orderId == ''){
          data = {
            order_type: 2, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, formId: formId, coupon_id: that.data.coupon_id, inviteUserId: wx.getStorageSync('inviteUserId')
          }
        }else{
          data = {
            order_type: 2, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, order_id: that.data.orderId, formId: formId, parent_id: that.data.parent_id, coupon_id: that.data.coupon_id,
            inviteUserId: wx.getStorageSync('inviteUserId')
          }
        }


        if(that.data.goodsDetails.info.goods_type == 0){//积分拼团
          this.submitOrders(data)
        }else{//实物和消费券拼团
          
          util.post(api.submitOrder, data).then((res) => {
            this.setData({ loading:true})
            if (res.errno == 0) {
              const orderId = res.data.orderInfo.id;
              wx.setStorageSync('goodsDetails', JSON.stringify(that.data.goodsDetails))
              if(res.data.orderInfo.actual_price == 0){
                util.showSuccessToast('支付成功')
              }else{
                wx.redirectTo({
                  url: `/pages/buy/buy?orderId=${orderId}&number=${that.data.number}&from=join&buyType=group`,
                })
              }
              this.setData({ loading: false })
            } else {
              this.setData({ loading: false })
              util.showErrorToast(res.errmsg)
            }
          }).catch((err)=>{
            this.setData({ loading: false })
          })
        }
    }
  },



  // 下单购买(正常单独团购)
  mySelfBuyGoods: function (e) {
    this.setData({ buyStatus: 0 })
    let formId = e.detail.formId
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        // collectBackImage: "/static/images/detail_back.png",
        price:that.data.goodsDetails.info.market_price
      });
    } else {//下单

      // 判断有无orderId,若有则请求参数中带上表示参加拼团，若无则不传表示发起拼团
      var data;
      if (that.data.orderId == '') {
        data = {
          order_type: 1, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, formId: formId, coupon_id: that.data.coupon_id, inviteUserId: wx.getStorageSync('inviteUserId')
        }
      } else {
        data = {
          order_type: 1, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, order_id: that.data.orderId, formId: formId, parent_id: that.data.parent_id, coupon_id: that.data.coupon_id,
          inviteUserId: wx.getStorageSync('inviteUserId')
        }
      }
      if (that.data.goodsDetails.info.goods_type == 0) {//积分拼团
        this.submitOrders(data)
      } else {//实物和消费券拼团
        util.post(api.submitOrder, data).then((res) => {
          this.setData({ loading: true })
          if (res.errno == 0) {
            const orderId = res.data.orderInfo.id;
            wx.setStorageSync('goodsDetails', JSON.stringify(that.data.goodsDetails))
            if (res.data.orderInfo.actual_price == 0) {
              util.showSuccessToast('支付成功')
            } else {
              wx.redirectTo({
                url: `/pages/buy/buy?orderId=${orderId}&number=${that.data.number}&from=join&buyType=group`,
              })
            }
            this.setData({ loading: false })
          } else {
            this.setData({ loading: false })
            util.showErrorToast(res.errmsg)          }
        }).catch((err)=>{
          this.setData({ loading: false })
        })
      }
    }
  },


  // 下单购买(其他人分享时参与拼团)
  takePartInGroup: function (e) {
    this.setData({ buyStatus: 1 })
    let formId = e.detail.formId
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        // collectBackImage: "/static/images/detail_back.png",
        price: that.data.goodsDetails.info.retail_price
      });
    } else {//下单

      // 判断有无orderId,若有则请求参数中带上表示参加拼团，若无则不传表示发起拼团
      var data;
      if (that.data.orderId == '') {
        data = {
          order_type: 2, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, formId: formId, coupon_id: that.data.coupon_id, inviteUserId: wx.getStorageSync('inviteUserId')
        }
      } else {
        data = {
          order_type: 2, cart_num: that.data.number, goods_id: that.data.goodsId, merchantId: that.data.goodsDetails.info.merchantId, storeId: that.data.goodsDetails.info.storeId, order_id: that.data.orderId, formId: formId, parent_id: that.data.parent_id, coupon_id: that.data.coupon_id,
          inviteUserId: wx.getStorageSync('inviteUserId')
        }
      }
      if (that.data.goodsDetails.info.goods_type == 0) {//积分拼团
        this.submitOrders(data)
      } else {//实物和消费券拼团
        util.post(api.submitOrder, data).then((res) => {
          this.setData({ loading: true })
          if (res.errno == 0) {
            const orderId = res.data.orderInfo.id;
            wx.setStorageSync('goodsDetails', JSON.stringify(that.data.goodsDetails))
            if (res.data.orderInfo.actual_price == 0) {
              util.showSuccessToast('支付成功')
            } else {
              wx.redirectTo({
                url: `/pages/buy/buy?orderId=${orderId}&number=${that.data.number}&from=join&buyType=group`,
              })
            }
            this.setData({ loading: false })
          } else {
            this.setData({ loading: false })
            util.showErrorToast(res.errmsg)
          }
        }).catch((err)=>{
          this.setData({ loading: false })
        })
      }
    }
  },

  // 收藏
  collect:function(){
    var that = this
    util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.goodsDetails.info.id }, "POST")
      .then(function (res) {
        if (res.errno == 0) {
          if (res.data.type == 'add') {
            that.setData({
              'collectBackImage': that.data.hasCollectImage
            });
          } else {
            that.setData({
              'collectBackImage': that.data.noCollectImage
            });
          }

        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }

      });
  },

  cutNumber: function () {
    var number = this.data.number

    this.setData({
      number: (this.data.number  > 1) ? this.data.number : 1,
      checkedSpecText:number
    });
    if(this.data.checkedSpecText == 0){
      this.setData({checkedSpecText:1})
    }
  },
  addNumber: function () {
    var number = this.data.number
    this.setData({
      number: this.data.number,
      checkedSpecText: number
    });

  },
  question(){
    util.request(api.question).then((res)=>{
      if(res.errno == 0){
        this.setData({question:res.data})
      }else{
        util.showErrorToast(res.msg)
      }
    })
  },
  submitOrders(data) {
    this.setData({ loading: true })
    let params = { 'userId': wx.getStorageSync('userId') }
    var confirm = (orderId) => {
      this.setData({ loading: false })
      wx.redirectTo({
        url: `/pages/success/success?orderId=${orderId}`,
      })
    }
    util.request(api.userInfo, params).then((res) => {
      // console.log('aaa', res)
      if (res.errno == 0) {
        let point = res.data.point
        if(this.data.buyStatus == 0){
          if (point < this.data.goodsDetails.info.market_price) {
            this.setData({ loading: false })
            util.showErrorToast('积分不足')
            return
          } else {
            util.post(api.submitOrder, data).then((res) => {
              if (res.errno == 0) {
                //积分拼团的回调
                const orderId = res.data.orderInfo.id;
                util.alert('购买成功', confirm(orderId))
              } else {
                this.setData({ loading: false })
                util.showErrorToast(res.errmsg)              }
            }).catch((err)=>{
              this.setData({ loading: false })
            })
          }
        } else{
          if (point < this.data.goodsDetails.info.retail_price) {
            this.setData({ loading: false })
            util.showErrorToast('积分不足')
            return
          } else {
            util.post(api.submitOrder, data).then((res) => {
              if (res.errno == 0) {
                //积分拼团的回调
                const orderId = res.data.orderInfo.id;
                util.alert('购买成功', confirm(orderId))
              } else {
                this.setData({loading:false})
                util.showErrorToast(res.errmsg)              }
            })
          }
        }
        
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // util.getRouter()
    util.getUrl()
    var that = this
    if(options.orderId != undefined){
      that.setData({orderId:options.orderId})
      util.request(api.orderDetails, { orderId: options.orderId }).then((res) => {
        if (res.errno == 0) {
          that.setData({ orderDetails: res.data })
        } else {
          util.showErrorToast(res.msg)
        }
      })
    }

    if (options.parent_id != undefined){
      this.setData({ parent_id: options.parent_id})
    }

    if (options.inviteUserId != undefined) {
      wx.setStorageSync('inviteUserId', options.inviteUserId)
    }
    
    this.setData({
      goodsId:options.id,
      type:options.type
    })
    
    

    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 100;
        // console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  call(){
    wx.makePhoneCall({
      phoneNumber: this.data.goodsDetails.applyStore.phone, 
      success: function () {
        // console.log("拨打电话成功！")
      },
      fail: function () {
        // console.log("拨打电话失败！")
      }
    })
  },
  goodsDetails(){
    var _this = this
    let data = { id: this.data.goodsId, referrer: 1 }
    util.request(api.goodsDetails, data).then((res1) => {    
      if(res1.errno==0){
        if (res1.data.userHasCollect == 1) {
          _this.setData({
            'collectBackImage': _this.data.hasCollectImage
          });
        } else {
          _this.setData({
            'collectBackImage': _this.data.noCollectImage
          });
        }
        

          // 获取当前的地理位置
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              lati = res.latitude
              longi = res.longitude
              // console.log('我的经纬度', lati, longi)
            }
          })
          // 实例化API核心类
          var qqMap = new QQMapWX({
            key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
          });
          qqMap.geocoder({
            address: res1.data.applyStore.address,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
            complete: res => {
              _this.setData({ businessAddress:res.result})
              // console.log('商家经纬度', _this.data.businessAddress.location);   //经纬度对象
              // 计算两地距离
              res1.data.applyStore.distance = util.getDistance(lati, longi, res.result.location.lat, res.result.location.lng)
            }
          });

        setTimeout(() => {
          _this.setData({
            hotRecommend: res1.data.recomdGoods,
            goodsDetails: res1.data
          })
        }, 500)

        this.setData({ loading: false })
        WxParse.wxParse('article', 'html', res1.data.info.goods_desc, _this);
        
      }else{
        util.showErrorToast('服务器异常')
      }
    }).catch((err)=>{
      this.setData({loading:false})
    })
  },


  // 倒计时
  daoshu: function () {
    // console.log(this.data.goodsDetails)
    if(this.data.goodsDetails){
      var obj = this.data.goodsDetails.info
      util.daoshu(obj)
      this.setData({ info: obj })
    }
  },

  setNumber(event){
    this.setData({ number: event.detail})
  },
  intoMap:function(){
    var _this = this
    var businessAddress = _this.data.businessAddress
    var address = businessAddress.address_components
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {  //因为这里得到的是你当前位置的经纬度
        var latitude = res.latitude
        var longitude = res.longitude
        wx.openLocation({        //所以这里会显示你当前的位置
          latitude: businessAddress.location.lat,
          longitude: businessAddress.location.lng,
          name: `${address.province}`,
          address: `${address.city}${address.district}${address.street}${address.street_number}`,
          scale: 28
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this
    this.goodsDetails()
    this.question()
    setInterval(function () {
      _this.daoshu()
    }, 1000);
  },

  // 热门推荐
  hot() {
    var _this = this
    util.request(api.hotCommend).then((res) => {
      // console.log('hot',res)
      if (res.errno == 0) {
        _this.setData({ hotRecommend: res.data.hotGoodsList })
      } else {
        util.alert(res.errmsg)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this = this
    // if (options.from == 'button') {
    console.log(`/pages/join/join?&id=${_this.data.goodsDetails.info.id}&type=self&inviteUserId=${wx.getStorageSync('userId')}`)
    return {
      title: _this.data.goodsDetails.info.name,
      imageUrl: _this.data.goodsDetails.gallery.length == 0 ? _this.data.goodsDetails.info.primary_pic_url_list[0] : _this.data.goodsDetails.gallery.length[0],
      path: `/pages/join/join?&inviteUserId=${wx.getStorageSync('userId')}&id=${_this.data.goodsDetails.info.id}&type=self`
    }
    // }
  }
})